##Get objects
old_ws = ls()

####################
#Tables Intolerance#
####################

#intolerance data
intol_vars = c('live_in_village', 'live_in_neighbor', 'rents_room', 'marries_child', 'build_relg_estab')

#trust vars
trust_vars= c('trust_relg_more', 'trust_ethnicity_more', 'relg_candidate')

#safe vars
safe_vars = c('village_safe')

#Keep close elections, muslim respondents
useTable_ifls = mergedTable_ifls[(sample_ni_it) & (relg %in% 1)]
useTable_ifls[, w_i := 1 / .N 
                   , by = list(kab_code, dapil_number, election_cycle, cluster, IT_win)]

#Unique dapil-election cycle id
useTable_ifls[, dapil_election_id := paste(kabupaten, dapil_number, election_cycle, sep= ":")]

#Set relg_candidate NA for missing data
useTable_ifls[relg_candidate %in% c(6,9), relg_candidate := NA]

#observed?
useTable_ifls[, obs_1 := !(noone_present)]
useTable_ifls[, obs_2 := (spouse_present) | (adult_hh_present) | (adult_nh_present)]
useTable_ifls[, obs_3 := (adult_nh_present)]


############################
#Create Dependent Variables#
############################

#Recode for "yes" as 1, all other responses as 0. (Indicates yes to intolerant attitude)
useTable_ifls[, paste0(intol_vars, "_b") := lapply(.SD, function(x) x %in% c(1)), .SDcols = intol_vars]

#Reverse coding so higher values indicate intolerance.
useTable_ifls[, c(intol_vars) := lapply(.SD, function(x) (x * -1) + 5), .SDcols = intol_vars]

#Intolerance index (mean)
useTable_ifls[, intol_mean := rowMeans(.SD), .SDcols = paste0(intol_vars, "")]


#Intolerance index (mean)
useTable_ifls[, intol_mean_b := rowMeans(.SD), .SDcols = paste0(intol_vars, "_b")]

#All intolerant values
useTable_ifls[, intol_all := rowSums(.SD) == 5 , .SDcols = paste0(intol_vars, "_b")]

#Any intolerant values
useTable_ifls[, intol_any := rowSums(.SD) > 0 , .SDcols = paste0(intol_vars, "_b")]

#SUm intolerant positions
useTable_ifls[, intol_count := rowSums(.SD), .SDcols = paste0(intol_vars, "_b")]

#Recode for "yes" as 1, all other responses as 0. (Indicates yes to untrustworthy)
useTable_ifls[, paste0(trust_vars, "_b") := lapply(.SD, function(x) x %in% c(1)), .SDcols = trust_vars]

#Recode for so greater trst for ingroup is higher
useTable_ifls[, c(trust_vars) := lapply(.SD, function(x) x*-1), .SDcols = trust_vars]

#Trust index (mean)
useTable_ifls[, trust_mean := rowMeans(.SD), .SDcols = paste0(trust_vars, "")]

#All untrusting values
useTable_ifls[, trust_all := rowSums(.SD) == 3 , .SDcols = paste0(trust_vars, "_b")]

#Any untrusting values
useTable_ifls[, trust_any := rowSums(.SD) > 0 , .SDcols = paste0(trust_vars, "_b")]

#SUm untrusting positions
useTable_ifls[, trust_count := rowSums(.SD), .SDcols = paste0(trust_vars, "_b")]

########################
#Intolerance indicators#
########################

attitudes_agg = useTable_ifls[, list(
  live_in_village = mean(live_in_village_b),
  live_in_neighbor = mean(live_in_neighbor_b),
  rents_room = mean(rents_room_b),
  marries_child = mean(marries_child_b),
  build_relg_estab = mean(build_relg_estab_b),
  intol_idx = mean(intol_count/5),
  intol_all = intol_all %>% mean,
  intol_any = intol_any %>% mean,
  intol_count = intol_count %>% mean,
  trust_relg_more = trust_relg_more %>% mean,
  trust_ethnicity_more = trust_ethnicity_more %>% mean,
  relg_candidate = relg_candidate %>% mean,
  untrust_idx = trust_mean %>% mean,
  untrust_all = trust_all %>% mean,
  untrust_any = trust_any %>% mean, 
  untrust_count = trust_count %>% mean,
  village_unsafe = village_safe %>% mean,
  village_unsafe_b = (village_safe == 4) %>% mean,
  dapil_cycle_n = .N
), by = list(kab_code, dapil_number, election_cycle, cluster, IT_win)]

#Model specifications
lm_specs = expand.grid(x = 'IT_win', 
                       y = c(intol_vars, paste0('intol', c('_idx', '_all', '_any')), 
                             trust_vars, paste0('untrust', c('_idx', '_all', '_any')),
                             'village_unsafe', 'village_unsafe_b' ),
                       stringsAsFactors = F
)


#Estimate
lm_models = Map(function(y,x) lm_loop(y,x, attitudes_agg),
                lm_specs$y, lm_specs$x)

###################
#Intolerance Items#
###################


#Get standard errors
table_list = c(lm_models[1:8])
table_se = lapply(table_list, function(x) cluster_errors(x, attitudes_agg[, cluster]) %>% diag %>% sqrt)

#Make table note
n_clusters = attitudes_agg$cluster %>% unique %>% length
n_respondents = attitudes_agg$dapil_cycle_n %>% sum
note_text = paste("Results for ", n_respondents, " collapsed to constituency-level means. Standard errors clustered by ", n_clusters, "constituency clusters.
                  Observations are constituencies in which the last seat was contested by
                  Islamist and secular parties with a margin less than 1 percent.
                  Intolerance measures indicate strong objection (1) or weak or no objection (0) to the following questions:
                  How do you feel if $\\dots$
                  (A) someone with a different faith from you lives in your village?
                  (B) someone with a different faith from you lives in your neighborhood?
                  (C) someone with a different faith from you rents a room from you?
                  (D) someone with a different faith from you marries one of your close relatives or children?
                  (E) people who have a different faith from you build a house of worship in your community?")

#Make table
table = stargazer(table_list, se = table_se, type = 'latex', 
                  title = "Effects of Islamist Victory on Self-reported Intolerance (IFLS)",
                  label = "tab:intolerance_binary_ifls_ni_it",
                  #out = './output/tables/intolerance_ni_it.tex',
                  column.separate = c(5,3),
                  column.labels = c('Intolerance Items', 'Index'),
                  multicolumn = T,
                  model.names = F,
                  model.numbers = T,
                  dep.var.labels = c("Village",  "Neighbor", "Room", "Marriage" , "Building" ,"Mean", "``All''", "``Any''"), 
                  dep.var.caption = "",
                  covariate.labels = c("Islamist Win"),
                  star.cutoffs = c(0.1, 0.05, 0.01),
                  #float.env = 'sidewaystable',
                  notes.align = 'l',
                  font.size = 'scriptsize',
                  keep.stat = 'n',
                  style='apsr')

write_latex(table[-10] %>% append(table[10], after = 10), note_text, './output/tables/table_e3.tex')


#Clean up
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)